<?php
class Personal_Model_MCart
{
    private $_uid;
    private $_conn;
    private $_collection;
    private $_db;
    public  $_cart;   
    public  $_cbooks  ;    // get a book info
    private $_function;

    public function  __construct($uid='') {
        $this->_uid = $uid;
        $this->_conn = new Mongo();
        $this->_db = $this->_conn->bookstore;
        $this->_collection = $this->_db->user_cart;
        $this->_cart = $this->_collection->findOne(array("uid"=>$this->_uid));
        $this->_cbooks = array();

        $this->_function=new Default_Model_MFunction();
    }
    
    private function getBookIDList(){

        $docFuser= $this->getFriendIdList();
        // get list book status
        if($this->_cart!=null){
            $uarr = $this->_cart["ubooks"];
            for ($index1 = 0; $index1 < count($this->_cart["ubooks"]); $index1++) {
                switch($uarr[$index1]["status"]){
                case "pushed":
                    $this->_cart["pushed"][]=$uarr[$index1];
                    break;
                case "transported":
                    $this->_cart["transported"][]=$uarr[$index1];
                    break;
                }
            }
        }
        elseif ($docFuser != null) $this->_cart = array();
        // get books friends bought
        if($docFuser != null){
            $fr_arr = $docFuser["friend"];
            for ($index = 0; $index < count($fr_arr); $index++) {
                $cart = new Personal_Model_MCart($fr_arr[$index]["fid"]);
                $this->_cart["fcart"][]=$cart["ubooks"];
            }
        }
    }
    
    private function getFriendIdList(){
        $docFuser = null;
        $collection = $this->_db->user_friend;
        if($collection!=null){
            $query = array("uid" => $this->_uid);
            $docFuser = $collection->findOne($query);
        }
        return $docFuser;
        /*
         * $docFuser
         * (
         *  uid:""
         "* friend"=>array(array("id_user"=>,..),array())
         * )
         */    
    }

    private function getRecommendedBookId(){
        $collection = $this->_db->recommendS_book;
        $query = array("id_user" => $this->_uid);
        $this->_recommendedlist = $collection->findOne($query);
        /*
         * _recommendedlist
         * (
         * "list_book_id"=>array('...','...');
         * )
         */
    }
    
    public function getBookLiteList(){
        $this->getBookIDList();
        /*
         * cart:
         * array(
         *'uid',
         *"ubooks" => array(array("bid"=>),array(),...)
         * "fcart"=>array(array("bid"),...)
         * 
         */
        if($this->_cart != null){
            $arr_item = array("pushed","transported","fcart");
            $array = $this->_cart;
            $book_infos = array();
            foreach ($arr_item as $value) {
                if(is_array($array[$value])){
                    for ($index = 0; $index < count($array[$value]); $index++) {
                        $book = new Admin_Model_MBook();
                        $book_infos = $book->getBookDetailById($array[$value][$index]["bid"]);
                        $this->_cbooks[$value][]=$book_infos;
                    }
                }
            }
        }
        /*
        $arr = $array["recommendedS"];
        for ($index1 = 0; $index1 < count($arr); $index1++) {
            $book->getBookInfo($arr[$index]);
            $arr[]["book_id"]=$book->$arr[$index];
            $arr[]["name"] = $book->getName();
            $arr[]["author"] = $book->getAuthor();
            $arr[]["category"] = $book->getCategory();
            $arr[]["cover"] = $book->getCover();
        }

        $arr = $array["friendcart"];
        for ($index2 = 0; $index2 < count($arr); $index2++) {
            $array_fr = $arr[$index2];
            foreach ($arr_type as $value) {
                for ($index = 0; $index < count($array_fr[$value]); $index++) {
                    $book->getBookInfo($array_fr[$value][$index]["book_id"]);
                    $array_fr[$value][$index]["name"]=$book->getName();
                    $array_fr[$value][$index]["author"]=$book->getAuthor();
                    $array_fr[$value][$index]["category"]=$book->getCategory();
                    $array_fr[$value][$index]["cover"]=$book->getCover();
                }
            }
        }
         * 
         */

        return $this->_cbooks;
    }

    // return false     => loi, khong them duoc
    // idcart           => them thanh cong 
    public function addCart($bid,$uid,$number,$idCart='')
    {
        $bookModel=new Admin_Model_MBook();
        if(!$bookModel->isExistBook($bid))
            return false;
        if(!is_int($number) || (is_int($number) && $number<=0))
            return false;

        $date=$this->_function->dateToString(Zend_Date::now());
        $oBid=new MongoId($bid);
        
        if($uid=='0') // nguoi dung public
        {
            $bookCart=array("id_book"=>$oBid,"number"=>$number,"date"=>$date,"order"=>1);
            $firsttime=true;
            $collection=$this->_db->user_cart_public;
            if($idCart!='' && $idCart!=null)      // kiem tra lan dau
            {
                try
                {
                    $oIdCart=new MongoId($idCart);
                    $document=$collection->findOne(array("_id"=>$oIdCart));
                    if($document!=null)
                        $firsttime=false;
                }
                catch(Exception $e)
                {
                    $firsttime=true;
                }
            }

            if($firsttime)  // chen vao lan dau
            {
                $newCart=array("cbooks"=>array($bookCart));
                $collection->insert($newCart);
                $docTemp=$collection->findOne($newCart);
                return $docTemp["_id"];
            }
            
            // chen tiep vao cart da co
            $oIdCart=new MongoId($idCart);
            $cartBook=$collection->findOne(array("_id"=>$oIdCart));
            if($cartBook!=null)
            {
                if(isset($cartBook["cbooks"]))
                {
                    $isInclude=false;
                    $tempNumber=0;
                    foreach($cartBook["cbooks"] as $aCartBook)
                    {
                        if($aCartBook["id_book"]==$oBid)
                        {
                            $isInclude=true;
                            $tempNumber=(int)$aCartBook["number"];
                            break;
                        }
                    }
                    if($isInclude)  // sach da co trong gio
                    {
                        $status=0;
                        $select = array("_id"=>$oIdCart,'cbooks.id_book'=>$oBid);
                        $total=$number+$tempNumber;
                        if($total>20)
                            $total=20;
                        $update = array('$set'=>array('cbooks.$.number'=>$total));
                        $collection->update($select,$update);
                        return $idCart;   
                    }
                    else            // them sach vao gio
                    {
                        $collection->update(array("_id"=>$oIdCart),array('$push'=>array("cbooks"=>$bookCart)));
                        return $idCart;
                    }
                }
            }
            
            return false;
        }

        // nguoi dung dang ky va da dang nhap
        $userModel=new Personal_Model_MUser();
        if(!$userModel->isExistedUser($uid))    // kiem tra nguoi dung co ton tai ko
        {
            return false;
        }

        $oUid=new MongoId($uid);
        $collection = $this->_db->user_cart;
        // kiem tra user trong collection user_cart
        $cartBook=$collection->findOne(array("id_user"=>$oUid));

        if($cartBook!=null) // them vao danh sach da co
        {
            if(isset($cartBook["cbooks"]))
            {
                $isInclude=false;
                $tempNumber=0;
                foreach($cartBook["cbooks"] as $aCartBook)
                {
                    if($aCartBook["id_book"]==$oBid)
                    {
                        $isInclude=true;
                        $tempNumber=(int)$aCartBook["number"];
                        break;
                    }
                }
                if($isInclude)  // sach da co trong gio
                {
                    $select = array("id_user"=>$oUid,'cbooks.id_book'=>$oBid);
                    $total=$number+$tempNumber;
                    if($total>20)
                        $total=20;
                    $update = array('$set'=>array('cbooks.$.number'=>$total));
                    $collection->update($select,$update);
                    
                    return $cartBook["_id"];
                }
                else            // them sach vao gio
                {
                    $bookCart=array("id_book"=>$oBid,"number"=>$number,"date"=>$date,"order"=>1);
                    $collection->update(array("id_user"=>$oUid),array('$push'=>array("cbooks"=>$bookCart)));
                    return $cartBook["_id"];
                }
            }
        }
        else // them moi
        {
            $bookCart=array("id_book"=>$oBid,"number"=>$number,"date"=>$date,"order"=>1);
            $newCart=array("id_user"=>$oUid,"cbooks"=>array($bookCart));
            $collection->insert($newCart);
            $docTemp=$collection->findOne($newCart);
            return $docTemp["_id"];
        }
        return false;
    }


    // chi su dung voi user public
    // neu idcart truyen vao la id cart cua nguoi dung dang ky
    // thi van ko tim thay
    // vi nguoi dung dang nhap lam viec qua user id
    protected function isExistCart($cid)
    {
        if($cid=='' || $cid==null)
            return false;
        $oCid=new MongoId($cid);
        $collection=$this->_db->user_cart_public;
        $document=$collection->findOne(array("_id"=>$oCid));
        if($document!=null && is_array($document) && count($document)>0)
        {
            return true;
        }
        return false;
    }
    
    public function getBookInCartByPersonal($uid)
    {
        if($uid!='' && $uid!=NULL)  // gio hang voi nguoi dang nhap
        {
            return $this->getBookInCartLogin($uid, true);
        }
        return array();
    }

    // lấy sách trong giỏ cả 2 trường hợp login và public
    // nếu 2 thông số không hợp lệ thì trả lại array()
    // nếu 1 thông số hợp lệ sẽ trả lại giỏ hàng tương ứng với thông số đó
    // kiểu trả lại là array(
    // nếu count(array()) = 0 tức là không có cuốn nào trong giỏ
    public function getBookInCart($uid='',$cid='')
    {
        if(($uid=='' && $cid=='')||($uid==NULL && $cid==NULL))
            return array();
        if($uid!='' && $uid!=NULL)  // gio hang voi nguoi dang nhap
        {
            //return 'uid';
            return $this->getBookInCartLogin($uid);
        }
        else if($cid!='' && $cid!=NULL) // gio hang voi nguoi public
        {
            //return 'cid:'.$cid;
            return $this->getBookInCartPublic($cid);
        }

        return array();
    }

    // lay sach trong gio, voi nguoi dung dang ky
    // sach lay ra theo thu tu thoi gian, sach moi nhat len tren
    protected function getBookInCartLogin($uid,$fullinfobook=false)
    {
        $userModel=new Personal_Model_MUser();
        if(!$userModel->isExistedUser($uid))
            return array();
        $collection=$this->_db->user_cart;
        $oUid=new MongoId($uid);
        $document=$collection->findOne(array("id_user"=>$oUid));
        if($document!=null && is_array($document) && count($document)>0)
        {
            $arrCart=$document["cbooks"];
            $bookcart=array();
            $bookModel=new Admin_Model_MBook();
            foreach($arrCart as $aBookCart)
            {
                if($fullinfobook==false)
                    $abook=$bookModel->getBookForPay($aBookCart["id_book"]);
                else
                    $abook=$bookModel->getBasicInfoBook($aBookCart["id_book"]);
                if(count($abook)>0)
                {
                    $abook["date"]=$aBookCart["date"];
                    $abook["number"]=$aBookCart["number"];
                    $abook["order"]=$aBookCart["order"];
                    array_push($bookcart, $abook);
                }
            }
            $this->_function->insertSort($bookcart, "date");
            return $bookcart;
        }
        return array();
    }

    // lay sach trong gio, voi nguoi dung public
    // sach lay ra theo thu tu thoi gian, sach moi nhat len tren
    protected function getBookInCartPublic($cid)
    {
        if(!$this->isExistCart($cid))
            return array();

        $collection=$this->_db->user_cart_public;
        $oCid=new MongoId($cid);
        $document=$collection->findOne(array("_id"=>$oCid));
        if($document!=null && is_array($document) && count($document)>0)
        {
            $arrCart=$document["cbooks"];
            $bookcart=array();
            $bookModel=new Admin_Model_MBook();
            foreach($arrCart as $aBookCart)
            {
                $abook=$bookModel->getBookForPay($aBookCart["id_book"]);
                if(count($abook)>0)
                {
                    $abook["date"]=$aBookCart["date"];
                    $abook["number"]=$aBookCart["number"];
                    $abook["order"]=$aBookCart["order"];
                    array_push($bookcart, $abook);
                }
            }
            $this->_function->insertSort($bookcart, "date");
            return $bookcart;
        }
        return array();
    }

    public function updateCart($uid,$cid,$arrbook=array())
    {
        if(($uid=='' && $cid=='')||($uid==NULL && $cid==NULL))
            return array();
        if($uid!='' && $uid!=NULL)  // gio hang voi nguoi dang nhap
        {
            return $this->updateCartLogin($uid, $arrbook);
        }
        else if($cid!='' && $cid!=NULL) // gio hang voi nguoi public
        {
            return $this->updateCartPublic($cid, $arrbook);
        }

        return false;
    }
    
    protected function updateCartLogin($uid,$arrbook=array())
    {
        $userModel=new Personal_Model_MUser();
        if(!$userModel->isExistedUser($uid))
            return false;
        $collection=$this->_db->user_cart;
        $oUid=new MongoId($uid);
        $document=$collection->findOne(array("id_user"=>$oUid));
        if($document!=null && is_array($document) && count($document)>0)
        {
            $arrCart=$document["cbooks"];
            foreach($arrCart as $aBookCart)
            {
                foreach($arrbook as $abook)
                {
                    if($aBookCart["id_book"] == $abook["id_book"])
                    {
                        if($aBookCart["order"] !=$abook["check"] || $aBookCart["number"]!=$abook["number"])
                        {
                            $select = array("id_user"=>$oUid,'cbooks.id_book'=>$abook["id_book"]);
                            $update = array('$set'=>array('cbooks.$.number'=>$abook["number"],'cbooks.$.order'=>$abook["check"]));
                            $collection->update($select,$update);
                        }
                        break;
                    }
                }
            }
        }
        return true;
    }
    
    protected function updateCartPublic($cid,$arrbook=array())
    {
        if(!$this->isExistCart($cid))
            return false;
        $collection=$this->_db->user_cart_public;
        $oCid=new MongoId($cid);
        $document=$collection->findOne(array("_id"=>$oCid));
        if($document!=null && is_array($document) && count($document)>0)
        {
            $arrCart=$document["cbooks"];
            foreach($arrCart as $aBookCart)
            {
                foreach($arrbook as $abook)
                {
                    if($aBookCart["id_book"] == $abook["id_book"])
                    {
                        if($aBookCart["order"] !=$abook["check"] || $aBookCart["number"]!=$abook["number"])
                        {
                            $select = array("_id"=>$oIdCart,'cbooks.id_book'=>$oBid);
                            $update = array('$set'=>array('cbooks.$.number'=>$abook["number"],'cbooks.$.order'=>$abook["check"]));
                            $collection->update($select,$update);
                        }
                        break;
                    }
                }
            }
        }
        return true;
    }

    // $uid : id nguoi mua
    // $cid : id cart trong truong hop mua public
    // $userBuy : thong tin nguoi mua
    // $uidReceive: id nguoi nhan, khi tang sach mot nguoi trong he thong
    // $userReceive : thong tin nguoi nhan
    // $message : tin nhan gui cho nguoi nhan sach trong truong hop tang sach
    // $typebuy : loai giao dich , 0 : mua sach, 1 : tang sach
    public function addOrder($uid,$cid,$userBuy,$uidReceive='',$userReceive=array(),$message='',$typebuy=0)
    {
        //return false;
        if(($uid=='' && $cid=='')||($uid==NULL && $cid==NULL))
            return false;
        if($uid!='' && $uid!=NULL)  // gio hang voi nguoi dang nhap
        {
            return $this->addOrderLogin($uid,$userBuy,$uidReceive,$userReceive,$message,$typebuy);
        }
        else if($cid!='' && $cid!=NULL) // gio hang voi nguoi public
        {
            return $this->addOrderPublic($cid,$userBuy,$userReceive,$message,$typebuy);
        }

        return false;
    }

    protected function addOrderLogin($uid,$userBuy,$uidReceive='',$userReceive=array(),$message='',$typebuy=0)
    {
        $bookInCart=$this->getBookInCartLogin($uid);
        $bookinterest=$this->_db->bookinterest;
        $mostbought=$this->_db->mostbought;
        foreach($bookInCart as $abook)
        {
            if((int)$abook["order"]==1)
            {
                $book=$bookinterest->findOne(array("id_book"=>new MongoId($abook["_id"])));
                // thiet lap totalmark de danh gia sach duoc quan tam nhat
                $totalmark=(int)$book["view"]+(int)$book["sumcomment"]+(int)$book["sumlike"]
                            +2*(int)$book["sumrating"]+3*(int)($abook["number"]+$book["sellnumber"]);
                $bookinterest->update($book,array('$set'=>array("totalmark"=>(int)$totalmark,
                                                  "sellnumber"=>(int)$abook["number"]+(int)$book["sellnumber"])));

                // cap nhat danh sach sach duoc mua nhieu nhat
                $mbook=$mostbought->findOne(array("id_book"=>new MongoId($abook["_id"])));
                if($mbook!=null)
                {
                    $mostbought->update($mbook,array('$set'=>array("quality"=>(int)$abook["number"]+(int)$mbook["quality"])));
                }
                else
                {
                    $count=$mostbought->find()->count();
                    if($count<30)
                    {
                        $newMostBought=array("id_book"=>new MongoId($abook["_id"]),"quality"=>(int)$abook["number"]);
                        $mostbought->insert($newMostBought);
                    }
                    else
                    {
                        //$minNumber=(int)$abook["number"];
                        $minNumber=1000;
                        foreach($mostbought->find() as $bookMB)
                        {
                            if((int)$bookMB["quality"]<$minNumber)
                            {
                                $minNumber=(int)$bookMB["quality"];
                            }
                        }
                        if($minNumber<(int)$abook["number"])
                        {
                            // xoa sach duoc mua it nhat
                            $deleteBook=$mostbought->findOne(array("quality"=>$minNumber));
                            $mostbought->remove($deleteBook);

                            // them sach moi
                            $newMostBought=array("id_book"=>new MongoId($abook["_id"]),"quality"=>(int)$abook["number"]);
                            $mostbought->insert($newMostBought);
                        }
                    }
                }
            }
        }

        $userModel=new Personal_Model_MUser();
        if(!$userModel->updateUserInfo($uid,$userBuy))
            return false;
        
        $bookOrder=array(); // danh sach sach dat mua
        $oUid=new MongoId($uid);
        $orderCollection=$this->_db->order;
        
        // lay ma don hang lon nhat
        $code_order=0;
        $listOrder=$orderCollection->find(array(),array("_id"=>true,"code_order"=>true));
        if($listOrder!=null && count($listOrder)>0)
        {
            foreach($listOrder as $aOrder)
            {
                if((int)$aOrder["code_order"]>$code_order)
                {
                    $code_order=(int)$aOrder["code_order"];
                }
            }
        }
        $code_order++;

        $cartCollection=$this->_db->user_cart;
        if($typebuy==0) // mua sach
        {
            // lay thong tin sach dat mua trong gio
            // xoa bo nhung quyen dat mua khoi gio
            foreach($bookInCart as $abook)
            {
                if((int)$abook["order"]==1)
                {
                    array_push($bookOrder, array("id_book"=>new MongoId($abook["_id"]),
                        "number"=>$abook["number"],"cost"=>$abook["cost"]));
                    //{ $pull : { field : {$elemMatch: {field2: value }} } }
                    //{ $pull : { field : {field2: value} } }
                    //$pull=array("cbooks"=>array('$elemMatch'=>array("id_book"=>new MongoId($abook["_id"]))));
                    $pull = array("cbooks"=>array("id_book"=>new MongoId($abook["_id"])));
                    
                    $cartCollection->update(array("id_user"=>$oUid),
                      array('$pull'=>$pull));
                }
            }
            if(count($bookOrder)==0)
                return false;

            // them sach dat mua vao collection order
            $date= $this->_function->dateToString(Zend_Date::now());
            $newOrder=array("id_user"=>$oUid,"code_order"=>$code_order,"type_user"=>1,"id_user_receive"=>$oUid,"book"=>$bookOrder,
                "date_order"=>$date,"status"=>0);
            $orderCollection->insert($newOrder);

            return true;
        }
        else if($typebuy==1)    // tang sach
        {
            foreach($bookInCart as $abook)
            {
                if((int)$abook["order"]==1)
                {
                    array_push($bookOrder, array("id_book"=>new MongoId($abook["_id"]),
                        "number"=>$abook["number"],"cost"=>$abook["cost"]));
                    //{ $pull : { field : {$elemMatch: {field2: value }} } }
                    //{ $pull : { field : {field2: value} } }
                    //$pull=array("cbooks"=>array('$elemMatch'=>array("id_book"=>new MongoId($abook["_id"]))));
                    $pull = array("cbooks"=>array("id_book"=>new MongoId($abook["_id"])));
                    
                    $cartCollection->update(array("id_user"=>$oUid),
                      array('$pull'=>$pull));
                }
            }
            if(count($bookOrder)==0)
                return false;

            if(count($userReceive)==0)
                return false;
            // them thong tin nguoi duoc tang vao user_info_public
            // lay id cua user do trong user_info_public
            $userPublicCollection=$this->_db->user_info_public;
            $userPublicCollection->insert($userReceive);
            $receive=$userPublicCollection->findOne($userReceive);
            $oUidReceive=new MongoId($receive["_id"]);
            
            $date= $this->_function->dateToString(Zend_Date::now());
            $newOrder=array("id_user"=>$oUid,"code_order"=>$code_order,"type_user"=>1,"id_user_receive"=>$oUidReceive,"book"=>$bookOrder,
                "date_order"=>$date,"status"=>0,"message"=>$message);

            $orderCollection->insert($newOrder);
            //gui tin nhan cho nguoi nhan
            $userModel->sendMessage($uid, $uidReceive, $message);
            return true;
        }
        
        return false;
    }

    protected function addOrderPublic($cid,$userBuy,$userReceive=array(),$message='',$typebuy=0)
    {
        $bookInCart=$this->getBookInCartPublic($cid);
        //$userModel=new Personal_Model_MUser();

        $bookinterest=$this->_db->bookinterest;
        $mostbought=$this->_db->mostbought;
        foreach($bookInCart as $abook)
        {
            if((int)$abook["order"]==1)
            {
                $book=$bookinterest->findOne(array("id_book"=>new MongoId($abook["_id"])));
                // thiet lap totalmark de danh gia sach duoc quan tam nhat
                $totalmark=(int)$book["view"]+(int)$book["sumcomment"]+(int)$book["sumlike"]
                            +2*(int)$book["sumrating"]+3*(int)($abook["number"]+$book["sellnumber"]);
                $bookinterest->update($book,array('$set'=>array("totalmark"=>(int)$totalmark,
                                                  "sellnumber"=>(int)$abook["number"]+(int)$book["sellnumber"])));

                // cap nhat danh sach sach duoc mua nhieu nhat
                $mbook=$mostbought->findOne(array("id_book"=>new MongoId($abook["_id"])));
                if($mbook!=null)
                {
                    $mostbought->update($mbook,array('$set'=>array("quality"=>(int)$abook["number"]+(int)$mbook["quality"])));
                }
                else
                {
                    $count=$mostbought->find()->count();
                    if($count<30)
                    {
                        $newMostBought=array("id_book"=>new MongoId($abook["_id"]),"quality"=>(int)$abook["number"]);
                        $mostbought->insert($newMostBought);
                    }
                    else
                    {
                        //$minNumber=(int)$abook["number"];
                        $minNumber=1000;
                        foreach($mostbought->find() as $bookMB)
                        {
                            if((int)$bookMB["quality"]<$minNumber)
                            {
                                $minNumber=(int)$bookMB["quality"];
                            }
                        }
                        if($minNumber<(int)$abook["number"])
                        {
                            // xoa sach duoc mua it nhat
                            $deleteBook=$mostbought->findOne(array("quality"=>$minNumber));
                            $mostbought->remove($deleteBook);
                            
                            // them sach moi
                            $newMostBought=array("id_book"=>new MongoId($abook["_id"]),"quality"=>(int)$abook["number"]);
                            $mostbought->insert($newMostBought);
                        }
                    }
                }    
            }
        }

        if(count($userBuy)==0)
            return false;
        $userPublicCollection=$this->_db->user_info_public;
        $userPublicCollection->insert($userBuy);
        $uid=$userPublicCollection->findOne($userBuy);
        $oUid=new MongoId($uid["_id"]);

        $bookOrder=array(); // danh sach sach dat mua
        $orderCollection=$this->_db->order;

        // lay ma don hang lon nhat
        $code_order=0;
        $listOrder=$orderCollection->find(array(),array("_id"=>true,"code_order"=>true));
        if($listOrder!=null && count($listOrder)>0)
        {
            foreach($listOrder as $aOrder)
            {
                if((int)$aOrder["code_order"]>$code_order)
                {
                    $code_order=(int)$aOrder["code_order"];
                }
            }
        }
        $code_order++;
        
        $cartCollection=$this->_db->user_cart_public;
        if($typebuy==0) // mua sach
        {
            // lay thong tin sach dat mua trong gio
            // xoa bo nhung quyen dat mua khoi gio
            foreach($bookInCart as $abook)
            {
                if((int)$abook["order"]==1)
                {
                    array_push($bookOrder, array("id_book"=>new MongoId($abook["_id"]),
                        "number"=>$abook["number"],"cost"=>$abook["cost"]));
                    //{ $pull : { field : {$elemMatch: {field2: value }} } }
                    //{ $pull : { field : {field2: value} } }
                    //$pull=array("cbooks"=>array('$elemMatch'=>array("id_book"=>new MongoId($abook["_id"]))));
                    $pull = array("cbooks"=>array("id_book"=>new MongoId($abook["_id"])));
                    
                    $cartCollection->update(array("_id"=>new MongoId($cid)),
                      array('$pull'=>$pull));
                }
            }
            if(count($bookOrder)==0)
                return false;

            // them sach dat mua vao collection order
            $date= $this->_function->dateToString(Zend_Date::now());
            $newOrder=array("id_user"=>$oUid,"code_order"=>$code_order,"type_user"=>-1,"id_user_receive"=>$oUid,"book"=>$bookOrder,
                "date_order"=>$date,"status"=>0);
            $orderCollection->insert($newOrder);

            return true;
        }
        else if($typebuy==1)    // tang sach
        {
            foreach($bookInCart as $abook)
            {
                if((int)$abook["order"]==1)
                {
                    array_push($bookOrder, array("id_book"=>new MongoId($abook["_id"]),
                        "number"=>$abook["number"],"cost"=>$abook["cost"]));
                    //{ $pull : { field : {$elemMatch: {field2: value }} } }
                    //{ $pull : { field : {field2: value} } }
                    //$pull=array("cbooks"=>array('$elemMatch'=>array("id_book"=>new MongoId($abook["_id"]))));
                    $pull = array("cbooks"=>array("id_book"=>new MongoId($abook["_id"])));
                    $cartCollection->update(array("id_user"=>$oUid),
                      array('$pull'=>$pull));
                }
            }
            if(count($bookOrder)==0)
                return false;

            if(count($userReceive)==0)
                return false;
            // them thong tin nguoi duoc tang vao user_info_public
            // lay id cua user do trong user_info_public
            $userPublicCollection->insert($userReceive);
            $receive=$userPublicCollection->findOne($userReceive);
            $oUidReceive=new MongoId($receive["_id"]);

            $date= $this->_function->dateToString(Zend_Date::now());
            $newOrder=array("id_user"=>$oUid,"code_order"=>$code_order,"type_user"=>-1,"id_user_receive"=>$oUidReceive,"book"=>$bookOrder,
                "date_order"=>$date,"status"=>0,"message"=>$message);

            $orderCollection->insert($newOrder);
            return true;
        }

        return false;
    }

    public function addBook($bid, $status="pushed", $quantity = 1, $info = ""){
        /*
         * them cung 1 sach da co trong gio, hoac mua nhieu quyen 1 luc
         */
        $isDone=0;
        $info = "";
        $date = date('Y-m-d H:m:s',time());
        $bstatus = $status;
        $newpb = array("_id"=>$bid,"info"=>$info, "date"=>$date, "status"=>$bstatus, "quantity"=>$quantity);
        if($this->_cart==null){
            $doc = array("_id"=>$this->_uid,"ubooks"=>array($newpb));
            $this->_collection->insert($doc);
            $isDone = 1;
        }
        else{
                        $existedB = FALSE;
                         /*
                         * neu sach da trong gio, se them so luong
                         * neu sach chua co, them sach voi so luong
                         */

                        for ($index = 0; $index < count($this->_cart["ubooks"]); $index++) {
                            if($this->_cart["ubooks"][$index]["_id"] == $bid){
                                $existedB = TRUE;
                                // them quantity
                                $select = array("uid"=>$this->_uid,"ubooks.bid"=>$bid);
                                $_quantity = $this->_cart["ubooks"][$index]["quantity"] + $quantity;
                                $query = array('$set'=>array("ubooks.$.quantity"=>$_quantity));
                                $this->_collection->update($select,$query);

                                $isDone = 1;
                                break;
                            }
                        }
     
                        if(!$existedB){
                                $select = array("uid"=>$this->_uid);
                                $query = array('$push'=>array("ubooks"=>$newpb));
                                $this->_collection->update($select,$query);
                                $isDone = 1;
                        }        
        }
        return $isDone;
    }

}
